//
//  LLSearchViewController.m
//  LLSearchView
//
//  Created by 王龙龙 on 2017/7/25.
//  Copyright © 2017年 王龙龙. All rights reserved.
//

#import "LLSearchViewController.h"
#import "LLSearchSuggestionVC.h"
#import "LLSearchView.h"
#import "ListNightSHTweetModel.h"
#import "MPMoviePlayerVC.h"
#import "PublicRightImageCell.h"
#import "PublicThreeImageCell.h"
#import "DiscoverTableViewCell.h"
#import <IQKeyboardManager.h>
#import "ListNightSHTweetModel.h"

@interface LLSearchViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) LLSearchView *searchView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *lbTitle;
@property (nonatomic, strong) NSMutableArray *hotArray;
@property (nonatomic, strong) NSMutableArray *historyArray;
//@property (nonatomic, strong) LLSearchSuggestionVC *searchSuggestVC;
@property (nonatomic, strong) ListNightSHTweetModel *tableViewModel;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *tableViewDataArr;

@property (nonatomic, strong) ListNightSHTweetModel *shareDataModel;

@end

@implementation LLSearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 回收键盘
    [self.searchBar resignFirstResponder];
    [[IQKeyboardManager sharedManager] setEnable:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getHotSearchData];
    [self setBarButtonItem];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.tableView.hidden = YES;
    
    if (!_searchBar.isFirstResponder) {
        [self.searchBar becomeFirstResponder];
    }
}

- (void)getHotSearchData {
    [PPNetworkHelper POST:URL_hotSearch parameters:nil success:^(id responseObject) {
        
        self.hotArray = responseObject[@"retBody"];
        if (!IsNotNilArr(self.hotArray)) {
            self.hotArray = [NSMutableArray arrayWithObjects:@"早安上海", @"夜上海", @"老字号", nil];
        }
        [self.view addSubview:self.searchView];
        [self.view addSubview:self.tableView];
    } failure:^(NSError *error) {
        
    }];
}

- (void)setBarButtonItem {
    // 创建搜索框
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 17, SCREEN_WIDTH, 34)];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 70, 34)];

    searchBar.placeholder = @"请输入购物关键词";
    searchBar.delegate = self;
    searchBar.showsCancelButton = NO;
    if (@available(iOS 13.0, *)) {
        UISearchTextField *searchTextField = searchBar.searchTextField;
        searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
        [searchBar setImage:[UIImage imageNamed:@"sort_magnifier"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    } else {
        UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
        searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
        [searchBar setImage:[UIImage imageNamed:@"sort_magnifier"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    }

    
    [titleView addSubview:searchBar];
    self.searchBar = searchBar;
    [self.searchBar becomeFirstResponder];
    self.navigationItem.titleView = titleView;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}
/** 点击取消 */
- (void)cancelDidClick {
    [self.searchBar resignFirstResponder];
    self.tableView.hidden = YES;
}

- (void)pushToSearchResultWithSearchStr:(NSString *)str {
    if (IsNotNilArr(self.tableViewDataArr)) {
        [self.tableViewDataArr removeAllObjects];
    }
    NSDictionary *par = @{@"title":str};
    [SXLoadingView showProgressHUD:nil];
    [PPNetworkHelper POST:URL_search parameters:par success:^(id responseObject) {
        [SXLoadingView hideProgressHUD];
        [self.searchBar resignFirstResponder];
        self.tableView.hidden = NO;
        NSArray *arr = responseObject[@"retBody"];
        if (IsNotNilArr(arr)) {
            self.tableViewDataArr = [ListNightSHTweetModel arrayOfModelsFromDictionaries:arr error:nil];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
    
    self.searchBar.text = str;
    [self setHistoryArrWithStr:str];
}

- (void)setHistoryArrWithStr:(NSString *)str {
    for (int i = 0; i < _historyArray.count; i++) {
        if ([_historyArray[i] isEqualToString:str]) {
            [_historyArray removeObjectAtIndex:i];
            break;
        }
    }
    [_historyArray insertObject:str atIndex:0];
    [NSKeyedArchiver archiveRootObject:_historyArray toFile:KHistorySearchPath];
}
#pragma mark - 友盟分享
- (void)shareAction:(UIButton *)sender {
    self.shareDataModel = self.tableViewDataArr[sender.tag - 1000];
    
    [self shareAlertView];
}

- (void)shareAlertView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //    蒙板
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.tag = 9998;
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    [window addSubview:view];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRemoveShareView:)];
    [view addGestureRecognizer:tap];
    
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT - 120 - 28, SCREEN_WIDTH - 32, 120)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.tag = 9999;
    ViewBorderRadius(whiteView, 10, 0, [UIColor whiteColor]);
    [window addSubview:whiteView];
    
    //间距
    float weight = 65;
    int range = (whiteView.frame.size.width - weight * 4) / 5;
    NSArray *arr = @[@"微信",
                     @"朋友圈",
                     @"QQ"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(range + i * (weight + range), 20, weight, weight)];
        [imageBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"分享%d", i]] forState:UIControlStateNormal];
        [imageBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        imageBtn.tag = i + 10000;
        [imageBtn setTitle:arr[i] forState:UIControlStateNormal];
        [whiteView addSubview:imageBtn];
        
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(range + i * (weight + range), GetViewYH(imageBtn), weight, 17)];
        lb.tag = i + 10010;
        lb.textColor = UIColorFromRGB(0x333333);
        lb.font = FONT(12);
        lb.text = arr[i];
        lb.textAlignment = 1;
        [whiteView addSubview:lb];
    }
    //    if (![QQApiInterface isQQInstalled]) {//没有安装QQ
    //        UIButton *btn = [whiteView viewWithTag:10002];
    //        btn.hidden = YES;
    //
    //        UILabel *lb = [whiteView viewWithTag:10012];
    //        lb.hidden = YES;
    //    }
    //    if (![WXApi isWXAppInstalled]) { //没有安装微信
    //        UIButton *btn0 = [whiteView viewWithTag:10000];
    //        UIButton *btn1 = [whiteView viewWithTag:10001];
    //        btn0.hidden = YES;
    //        btn1.hidden = YES;
    //
    //        UILabel *lb0 = [whiteView viewWithTag:10010];
    //        UILabel *lb1 = [whiteView viewWithTag:10011];
    //        lb0.hidden = YES;
    //        lb1.hidden = YES;
    //    }
}

- (void)shareBtnAction:(UIButton *)sender {
    [self removeShareView];
    NSInteger platformType = 0;
    switch (sender.tag) {
            case 10000: {
                platformType = 1;//微信聊天
            }
            break;
            case 10001: {
                platformType = 2;//微信朋友圈
            }
            break;
            case 10002: {
                platformType = 4;//QQ聊天
            }
            break;
            case 10003: {
                
                if ([UserManager sharedUserManager].isLogin) {
                    NSString *str = [NSString stringWithFormat:@"%@", self.shareDataModel.id];
                    NSDictionary *par = @{@"userId":DSStringValue([UserManager sharedUserManager].userInfo.uid),
                                          @"tweetId":str
                                          };
                    
                    [PPNetworkHelper POST:URL_addCollect parameters:par success:^(id responseObject) {
                        [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
                    } failure:^(NSError *error) {
                        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
                    }];
                } else {
                    LoginAndRegisterVC *vc = [[LoginAndRegisterVC alloc] init];
                    vc.hidesBottomBarWhenPushed = YES;
                    vc.pushType = 1;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                return;
            }
            break;
            
        default:
            break;
    }
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString *thumbURL = [NSString stringWithFormat:@"%@", self.shareDataModel.imgPath[0]];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@", self.shareDataModel.fromName] descr:[NSString stringWithFormat:@"%@", self.shareDataModel.title] thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = [NSString stringWithFormat:@"%@", self.shareDataModel.linkPath];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************分享失败 %@*********",error);
        } else {
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"响应消息 %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"原始响应数据 %@",resp.originalResponse);
            } else {
                UMSocialLogInfo(@"响应数据 %@",data);
            }
        }
    }];
}

- (void)tapRemoveShareView:(UITapGestureRecognizer *)tap {
    [self removeShareView];
}

- (void)removeShareView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIView *view0 = [window viewWithTag:9998];
    UIView *view1 = [window viewWithTag:9999];
    
    [view0 removeFromSuperview];
    [view1 removeFromSuperview];
}
#pragma mark - UISearchBarDelegate - 代理
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self pushToSearchResultWithSearchStr:searchBar.text];
    [self.searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
    self.tableView.hidden = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchBar.text == nil || [searchBar.text length] <= 0) {
        self.tableView.hidden = YES;
    }
}
#pragma mark - UITableViewDelegate - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWitMsg:@"没有搜索到该数据哦～" ifNecessaryForRowCount:self.tableViewDataArr.count image:@"搜索空"];
    return self.tableViewDataArr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    ListNightSHTweetModel *model = self.tableViewDataArr[indexPath.row];
    /**
     1一张图 2三张图 3视频
     */
    if (model.cssType == 3) {
        MPMoviePlayerVC *vc = [[MPMoviePlayerVC alloc] init];
        vc.videoTitle = DSStringValue(model.title);
        vc.videoPath = DSStringValue(model.videoPath);
        vc.fromName = DSStringValue(model.fromName);
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:DSStringValue(model.linkPath)];
        webVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ListNightSHTweetModel *model = self.tableViewDataArr[indexPath.row];
    /**
     1一张图 2三张图 3视频
     */
    switch (model.cssType) {
            case 1:{//一张小图
                static NSString *CellIdentifier = CellID_PublicRightImageCell;
                PublicRightImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[PublicRightImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.shareBtn.tag = 1000 + indexPath.row;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updatePublicRightImageCellWithModel:model];
                return cell;
            }
            break;
            case 2:{//三张小图
                static NSString *CellIdentifier = CellID_PublicThreeImageCell;
                PublicThreeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[PublicThreeImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.shareBtn.tag = 1000 + indexPath.row;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updatePublicThreeImageCellWithModel:model];
                return cell;
            }
            break;
            case 3:{//视频
                static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
                DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.imageVideo.hidden = NO;
                cell.shareBtn.tag = 1000 + indexPath.row;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updateDiscoverTableViewCellWithModel:model];
                return cell;
            }
            break;
            case 4: {//一张大图
                static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
                DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.imageVideo.hidden = YES;
                cell.shareBtn.tag = 1000 + indexPath.row;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updateDiscoverTableViewCellWithModel:model];
                return cell;
            }
            break;
        default:{//一张大图
            static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
            DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.imageVideo.hidden = YES;
            cell.shareBtn.tag = 1000 + indexPath.row;
            [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell updateDiscoverTableViewCellWithModel:model];
            return cell;
        }
            break;
    }
}

#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DiscoverTableViewCell" bundle:nil] forCellReuseIdentifier:CellID_DiscoverTableViewCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicRightImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicRightImageCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicThreeImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicThreeImageCell];
    }
    return _tableView;
}


- (NSMutableArray *)tableViewDataArr {
    if (!_tableViewDataArr) {
        _tableViewDataArr = [[NSMutableArray alloc] init];
    }
    return _tableViewDataArr;
}

- (NSMutableArray *)hotArray {
    if (!_hotArray) {
//        self.hotArray = [NSMutableArray arrayWithObjects:@"早安上海", @"夜上海", @"老字号", nil];
    }
    return _hotArray;
}

- (NSMutableArray *)historyArray {
    if (!_historyArray) {
        _historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:KHistorySearchPath];
        if (!_historyArray) {
            self.historyArray = [NSMutableArray array];
        }
    }
    return _historyArray;
}

- (LLSearchView *)searchView {
    if (!_searchView) {
        self.searchView = [[LLSearchView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 100) hotArray:self.hotArray historyArray:self.historyArray];
        __weak LLSearchViewController *weakSelf = self;
        _searchView.tapAction = ^(NSString *str) {
            [weakSelf pushToSearchResultWithSearchStr:str];
        };
    }
    return _searchView;
}


//- (LLSearchSuggestionVC *)searchSuggestVC
//{
//    if (!_searchSuggestVC) {
//        self.searchSuggestVC = [[LLSearchSuggestionVC alloc] init];
//        _searchSuggestVC.view.frame = CGRectMake(0, 100, KScreenWidth, KScreenHeight - 100);
//        _searchSuggestVC.view.hidden = YES;
//        __weak LLSearchViewController *weakSelf = self;
//        _searchSuggestVC.searchBlock = ^(NSString *searchTest) {
//            [weakSelf pushToSearchResultWithSearchStr:searchTest];
//        };
//    }
//    return _searchSuggestVC;
//}


@end
